package net.ankao.job.startup;

import lombok.extern.slf4j.Slf4j;
import net.ankao.framework.starter.admin.service.EcMenuService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;

/**
 * @author LILU
 * @date 2025-01-24 8:59
 */
@Slf4j
@Order(Integer.MIN_VALUE)
@Component
public class InitDbRunner implements CommandLineRunner {

    @Resource
    private DataSource dataSource;

    @Resource
    private EcMenuService menuService;

    @Override
    public void run(String... args) throws Exception {
        try (Connection connection = dataSource.getConnection()) {
            // 执行SQL文件
            ScriptUtils.executeSqlScript(connection, new ClassPathResource("init/initTable.txt"));
            int count = menuService.count();
            if (count == 0) {
                ScriptUtils.executeSqlScript(connection, new ClassPathResource("init/initData.txt"));
            }
        }catch (Exception e){
            log.info(e.getMessage(),e);
        }
    }
}
